package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import oracle.jrockit.jfr.openmbean.ProducerDescriptorType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class StorageTccActionImpl implements StorageTccAction{
    @Autowired
    private StorageMapper storageMapper;

    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage=storageMapper.selectById(productId);
        if (storage.getResidue() < count){
            throw new RuntimeException("库存不足");//库存不足，不能进行冻结操作
        }
        storageMapper.updateResidueToFrozen(productId, count);
        // 第一阶段成功，保存一个一阶段的成功标记
        ResultHolder.setResult(StorageTccAction.class,ctx.getXid(),"p" );
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext ctx) {
        if(ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }

        Long product = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(product, count);
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if(ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }
        Long product = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(product, count);

        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
}
